package com.lincoln.framework.exception;

import com.lincoln.framework.common.MessageHandlerEx;
import com.lincoln.framework.utils.FrameworkLogger;
import com.lincoln.framework.utils.StringUtilsEx;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 异常处理
 * 
 * @author zwm
 * 
 * @version 2016-2-25 下午2:35:19
 */
public class FrameworkExceptionHandler implements HandlerExceptionResolver {

	private static FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(FrameworkExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		try {
			// TODO 具体异常需要进一步处理
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("exception", ex);
			
			// 异常类型，是否刷新参数
			String errorType = "";
			boolean needRefresh = false;
			boolean isSystemError = true;
			if (ex instanceof ClientException) {
				isSystemError = false;
				errorType = ((ClientException) ex).getErrorType();
				needRefresh = ((ClientException) ex).isNeedRefresh();
			}
			if (ex instanceof SystemException) {
				errorType = ((SystemException) ex).getErrorType();
				needRefresh = ((SystemException) ex).isNeedRefresh();
			}
			try {
				if(isSystemError) {
					logger.error("【异常消息:" + ex.getMessage() + "】【参数：" + StringUtilsEx.getJsonString(request.getParameterMap())
							+ "】", ex);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			
			// ajax处理数据
			if (isAjaxRequest(request)) {
				Map<String, Object> ajaxReturnData = new HashMap<String, Object>();
				ajaxReturnData.put("errorType", errorType);
				ajaxReturnData.put("needRefresh", needRefresh);
				MessageHandlerEx.instance(request, response).ajaxErrorReturn(ex.getMessage(), ajaxReturnData);
				return null;
			}
			
			model.put("errorType", errorType);
			model.put("needRefresh", needRefresh);
			model.put("uri", request.getRequestURI());
			// 其他处理跳转统一异常页面
			
			if(request.getRequestURI().indexOf("/sys/") == -1){
				return new ModelAndView("exception/error_site", model);
			}
			return new ModelAndView("exception/error", model);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return null;
	}

	/**
	 * 是否ajax请求
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		return request.getHeader("x-requested-with") != null
				&& request.getHeader("x-requested-with").trim().toLowerCase().equals("xmlhttprequest");
	}

	/**
	 * 取错误信息前40个字符作为邮件标题
	 * 
	 * @param content
	 * @return
	 */
	private String getEmailTitle(String content) {
		int titleLength = 40;
		if (content != null && content.length() > titleLength) {
			return content.substring(0, titleLength - 1);
		} else {
			return content;
		}
	}
}
